package com.whj.wkpt.controller;

import com.whj.wkpt.dto.PageResultDTO;
import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.TaskApplication;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.service.TaskApplicationService;
import com.whj.wkpt.service.TaskService;
import com.whj.wkpt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class HomeController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;
    
    @Autowired
    private TaskApplicationService taskApplicationService;

    /**
     * 首页控制器，处理任务的条件查询和分页显示
     * 支持按任务标题和任务状态进行条件查询
     * 
     * @param title 任务标题查询条件（可选）
     * @param taskStatus 任务状态查询条件（可选）
     * @param page 当前页码，默认为0
     * @param size 每页显示记录数，默认为6
     * @param model 视图模型
     * @param authentication 用户认证信息
     * @return 返回首页视图
     */
    @GetMapping("/")
    public String home(@RequestParam(required = false) String title,
                       @RequestParam(required = false) String taskStatus,
                       @RequestParam(defaultValue = "0") int page,
                       @RequestParam(defaultValue = "6") int size,
                       Model model, Authentication authentication) {
        // 获取所有任务并进行分页
        PageResultDTO<Task> pageResult = taskService.findTasksWithPagination(title, taskStatus, page, size);
        model.addAttribute("tasks", pageResult.getContent());
        model.addAttribute("currentPage", pageResult.getPage());
        model.addAttribute("totalPages", pageResult.getTotalPages());
        model.addAttribute("totalElements", pageResult.getTotalElements());
        model.addAttribute("title", title);
        model.addAttribute("taskStatus", taskStatus);
        
        // 如果用户已登录，获取用户信息
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            User user = userService.findByUsername(username).orElse(null);
            model.addAttribute("currentUser", user);
            
            // 如果是威客用户，获取可申请的任务
            if (user != null && "freelancer".equals(user.getRole())) {
                // 获取可申请的任务并进行分页
                PageResultDTO<Task> availableTasksPageResult = taskService.findTasksWithPagination(title, taskStatus, page, size);
                model.addAttribute("availableTasks", availableTasksPageResult.getContent());
                model.addAttribute("availableTasksCurrentPage", availableTasksPageResult.getPage());
                model.addAttribute("availableTasksTotalPages", availableTasksPageResult.getTotalPages());
                model.addAttribute("availableTasksTotalElements", availableTasksPageResult.getTotalElements());
            }
            
            // 如果是雇主用户，获取任务承接信息
            if (user != null && "employer".equals(user.getRole())) {
                // 获取雇主发布的任务
                List<Task> employerTasks = taskService.findByEmployerId(user.getUserId());
                model.addAttribute("employerTasks", employerTasks);
                
                // 获取这些任务的承接情况
                List<Long> employerTaskIds = employerTasks.stream()
                        .map(Task::getTaskId)
                        .collect(Collectors.toList());
                
                if (!employerTaskIds.isEmpty()) {
                    List<TaskApplication> taskApplications = taskApplicationService.findByTaskIds(employerTaskIds);
                    model.addAttribute("taskApplications", taskApplications);
                    
                    // 获取任务标题信息
                    Map<Long, Task> taskMap = employerTasks.stream()
                            .collect(Collectors.toMap(Task::getTaskId, task -> task));
                    model.addAttribute("taskMap", taskMap);
                }
            }
        }
        
        return "index";
    }

    @GetMapping("/home")
    public String homePage(@RequestParam(required = false) String title,
                           @RequestParam(required = false) String taskStatus,
                           @RequestParam(defaultValue = "0") int page,
                           @RequestParam(defaultValue = "6") int size,
                           Model model, Authentication authentication) {
        // 获取所有任务并进行分页
        PageResultDTO<Task> pageResult = taskService.findTasksWithPagination(title, taskStatus, page, size);
        model.addAttribute("tasks", pageResult.getContent());
        model.addAttribute("currentPage", pageResult.getPage());
        model.addAttribute("totalPages", pageResult.getTotalPages());
        model.addAttribute("totalElements", pageResult.getTotalElements());
        model.addAttribute("title", title);
        model.addAttribute("taskStatus", taskStatus);
        
        // 如果用户已登录，获取用户信息
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            User user = userService.findByUsername(username).orElse(null);
            model.addAttribute("currentUser", user);
            
            // 如果是威客用户，获取可申请的任务
            if (user != null && "freelancer".equals(user.getRole())) {
                // 获取可申请的任务并进行分页
                PageResultDTO<Task> availableTasksPageResult = taskService.findTasksWithPagination(title, taskStatus, page, size);
                model.addAttribute("availableTasks", availableTasksPageResult.getContent());
                model.addAttribute("availableTasksCurrentPage", availableTasksPageResult.getPage());
                model.addAttribute("availableTasksTotalPages", availableTasksPageResult.getTotalPages());
                model.addAttribute("availableTasksTotalElements", availableTasksPageResult.getTotalElements());
            }
            
            // 如果是雇主用户，获取任务承接信息
            if (user != null && "employer".equals(user.getRole())) {
                // 获取雇主发布的任务
                List<Task> employerTasks = taskService.findByEmployerId(user.getUserId());
                model.addAttribute("employerTasks", employerTasks);
                
                // 获取这些任务的承接情况
                List<Long> employerTaskIds = employerTasks.stream()
                        .map(Task::getTaskId)
                        .collect(Collectors.toList());
                
                if (!employerTaskIds.isEmpty()) {
                    List<TaskApplication> taskApplications = taskApplicationService.findByTaskIds(employerTaskIds);
                    model.addAttribute("taskApplications", taskApplications);
                    
                    // 获取任务标题信息
                    Map<Long, Task> taskMap = employerTasks.stream()
                            .collect(Collectors.toMap(Task::getTaskId, task -> task));
                    model.addAttribute("taskMap", taskMap);
                }
            }
        }
        
        return "index";
    }
}